/**
 * Created by Brook on 2020/4/9.
 */

(function () {
    var async = require('async');
    var http = require('http')
    var moment = require('moment')
    var sql_config = require('../../serverconfig.js');
    var model_sql = require('../../tool/db_helper.js').init(sql_config.Model_Config);
    var SQL_TXT = sql_config.SQL_TXT;
    var request = require('request');


    //接收请求 - 接收解析状态
    exports.post_receiveState = function(req, res) {
        var data = {
            "message": "请求成功",
            "data": {
                "code": 200,
                "message": ''
            }
        };

        async.auto({
            check_pars:function(cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body)
            },
            response:['check_pars', function (cb, result) {
                cb(null, []);
            }],
            //获取uuid
            get_fileID:['response', function (cb, result) {
                var {uuid} = result.check_pars;
                //查询数据
                model_sql.query(SQL_TXT.get_fileId_uuid, [uuid],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            //更新状态
            up_state:['get_fileID', function (cb, result) {
                if (result.get_fileID.length == 0) {
                    console.log('data length 0')
                    data.data.code = 201;
                    data.data.message = '无效的UUID';
                    res.json(data);
                } else {
                    var {uuid,parsingCode,parsingMessage,parsingType} = result.check_pars;
                    //查询数据
                    model_sql.query(SQL_TXT.up_state, [parsingType, parsingCode, parsingMessage, uuid],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                };
            }],
            //记录状态日志
            insert_log:['up_state', function (cb, result) {
                var {uuid,parsingCode,parsingMessage,parsingType} = result.check_pars;
                var info = [];
                info = [
                    uuid,
                    result.get_fileID[0].fileid,
                    parsingType,
                    parsingCode,
                    parsingMessage,
                    moment().format('YYYYMMDD'),
                    moment().format('YYYY-MM-DD HH:mm:ss')
                ];
                model_sql.query(SQL_TXT.insert_logs, [info],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            //获取modelId
            get_modelId:['insert_log', function (cb, result) {
                if(result.get_fileID.length != 0) {
                    model_sql.query(SQL_TXT.get_modelId, [result.get_fileID[0].id],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                } else {
                    cb()
                };
            }],
            //判断状态是否发送
            check_notice:['get_modelId', function (cb, result) {
                var {parsingType} = result.check_pars;
                if (parsingType == 3 || parsingType == 4){
                    //modelId
                    if (result.get_modelId){
                        if (result.get_modelId.length != 0) {
                            result.check_pars['modelId'] = result.get_modelId[0].modelid
                        } else {
                            result.check_pars['modelId'] = ''
                        }
                    } else {
                        result.check_pars['modelId'] = ''
                    }
                    if (result.get_fileID.length == 0) {
                        cb()
                    } else {
                        console.log('发送回调接口');
                        result.check_pars['fileId'] = result.get_fileID[0].fileid
                        //console.log(result.check_pars)
                        httprequest(result.get_fileID[0].notifyurl, result.check_pars,1,cb);
                        cb()
                    }
                } else {
                    cb()
                };
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json({});
            }else{
                res.json(data);
                //console.log(r);
            };
        });
    };


    //接收请求 - 获取解析进度
    exports.post_getState = function(req, res) {
        async.auto({
            check_pars:function(cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body)
            },
            get_state:['check_pars', function (cb, result) {
                model_sql.query(SQL_TXT.get_state, [result.check_pars.fileId],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            response:['get_state', function (cb, result) {
                if (result.get_state.length != 0) {
                    res.json(result.get_state[0]);
                } else {
                    res.json('0');
                }
                cb(null, []);
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json(r);
            }else{
                //console.log(r);
            };
        });
    };


    //接收请求 - 取消任务
    exports.post_closeTask = function(req, res) {
        var data = {
            "message": "请求成功",
            "data": {
                "code": 200,
                "message": '未查找到该任务'
            }
        };
        async.auto({
            check_pars:function(cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body)
            },
            get_task:['check_pars', function (cb, result) {
                model_sql.query(SQL_TXT.get_task, [result.check_pars.uuid],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            delete_task:['get_task', function (cb, result) {
                if (result.get_task.length == 0) {
                    data.data.code = 201;
                    data.data.message = '未查找到该任务';
                    res.json(data);
                } else {
                    model_sql.query(SQL_TXT.delete_list, [result.check_pars.uuid],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                };
            }],
            delete_info:['delete_task', function (cb, result) {
                model_sql.query(SQL_TXT.delete_info, [result.get_task[0].id],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            response:['delete_info', function (cb, result) {
                data.data.message = '任务删除成功';
                res.json(data);
                cb();
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json();
            }else{
                //console.log(r);
            };
        });
    };


    //接收请求 - 记录附加属性
    exports.post_attribute = function(req, res) {
        var data = {
            "message": "请求成功",
            "data": {
                "code": 200,
                "message": '未查找到该任务'
            }
        };
        async.auto({
            check_pars:function(cb){
                res.header('Access-Control-Allow-Origin', '*');
                cb(null, req.body)
            },
            //获取listid
            check_uuid:['check_pars', function (cb, result) {
                model_sql.query(SQL_TXT.get_modellist, [result.check_pars.uuid],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            check_listid:['check_uuid', function (cb, result) {
                if (result.check_uuid.length == 0) {
                    data.data.code = 201;
                    data.data.message = '无效的uuid, 未查询到';
                    res.json(data);
                } else {
                    model_sql.query(SQL_TXT.get_attributes, [result.check_uuid[0].id],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                };
            }],
            insert_listid:['check_listid', function (cb, result) {
                if (result.check_listid.length == 0) {
                    var info = [];
                    info = [
                        result.check_uuid[0].id,
                        moment().format('YYYYMMDD'),
                        moment().format('YYYY-MM-DD HH:mm:ss')
                    ];
                    model_sql.query(SQL_TXT.insert_attributes, [info],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result.insertId);
                    });
                } else {
                    cb(null, result.check_listid[0].id);
                };
            }],
            check_type:['insert_listid', function (cb, result) {
                var data = result.check_pars;
                var type = 0;
                for (var i in data){
                    if (i == 'localPath') {
                        type = 1;
                    } else if (i == 'md5') {
                        type = 2;
                    } else if (i == 'ended') {
                        type = 3;
                    };
                };
                cb(null, type);
            }],
            update_attributes_a:['check_type', function (cb, result) {
                var info_id = result.insert_listid;
                var data = result.check_pars;
                var setdata = '';
                if (result.check_type == 1) {
                    for (var i in data){
                        if (i != 'uuid' && i != 'status' && i != 'message'){
                            setdata += i + " = '" + data[i] + "', "
                        };
                    };
                    setdata = setdata.substr(0,setdata.length-2);
                    setdata = setdata.replace('localPath', 'localpath');
                    setdata = setdata.replace('errorPath', 'skppath_error');

                    var UpSql = SQL_TXT.update_attributes + setdata +' WHERE id = '+info_id+';';
                    model_sql.query(UpSql,function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result.insertId);
                    });
                } else {
                    cb(null, []);
                };
            }],
            update_attributes_b:['update_attributes_a', function (cb, result) {
                var info_id = result.insert_listid;
                var data = result.check_pars;
                var setdata = '';
                if (result.check_type == 2) {
                    for (var i in data){
                        if (i != 'uuid' && i != 'status' && i != 'message' && i != 'md5' && i != 'modelId' && i != 'path'){
                            setdata += i + " = '" + data[i] + "', "
                        };
                    };
                    setdata = setdata.substr(0,setdata.length-2);
                    setdata = setdata.replace('errorPath', 'pbcpath_error');

                    var UpSql = SQL_TXT.update_attributes + setdata +' WHERE id = '+info_id+';';
                    model_sql.query(UpSql,function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result.insertId);
                    });
                } else {
                    cb(null, []);
                };
            }],
            update_attributes_c:['update_attributes_b', function (cb, result) {
                var info_id = result.insert_listid;
                var data = result.check_pars;
                var setdata = '';
                if (result.check_type == 3) {
                    for (var i in data){
                        if (i != 'uuid' && i != 'status' && i != 'message' && i != 'modelId'){
                            setdata += i + " = '" + data[i] + "', "
                        };
                    };
                    setdata = setdata.substr(0,setdata.length-2);
                    setdata = setdata.replace('jsonInPath', 'jsoninpath');
                    setdata = setdata.replace('errorPath', 'jsonpath_error');

                    var UpSql = SQL_TXT.update_attributes + setdata +' WHERE id = '+info_id+';';
                    model_sql.query(UpSql,function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result.insertId);
                    });
                } else {
                    cb(null, []);
                };
            }],
            up_md5:['update_attributes_c', function (cb, result) {
                if (result.check_type == 2) {
                    var data = result.check_pars;
                    model_sql.query(SQL_TXT.attribute_up_md5, [data.md5, data.uuid],function(db_err,db_result){
                        db_err?cb(db_err):cb(null,db_result);
                    });
                } else {
                    cb(null, []);
                };
            }],
            up_modelId:['up_md5', function (cb, result) {
                if (result.check_type == 2 || result.check_type == 3) {
                    var data = result.check_pars;
                    var info_id = result.insert_listid;

                    model_sql.query(SQL_TXT.get_modelinfo, [result.check_uuid[0].id],function(db_err,db_result){
                        if(db_err) {
                            cb(db_err)
                        } else {
                            if (db_result.length == 0) {
                                var info = [];
                                info = [
                                    result.check_uuid[0].id,
                                    data.modelId,
                                    ,
                                    ,
                                    moment().format('YYYYMMDD'),
                                    moment().format('YYYY-MM-DD HH:mm:ss')
                                ];
                                model_sql.query(SQL_TXT.insert_modelinfo, [info],function(db_err,db_result){
                                    db_err?cb(db_err):cb(null,db_result);
                                });
                            } else {
                                model_sql.query(SQL_TXT.attribute_up_modelId, [data.modelId, result.check_uuid[0].id],function(db_err,db_result){
                                    db_err?cb(db_err):cb(null,db_result);
                                });
                            };
                        };
                    });
                } else {
                    cb(null, []);
                };
            }],
            //回传数据
            response_data:['up_modelId', function (cb, result) {
                var data = {
                    "message": "请求成功",
                    "data": {
                        "code": 200,
                        "data": []
                    }
                };
                console.log("Response request data success ...")
                res.json(data);
                cb()
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json();
            }else{
                //console.log(r);
            };
        });
    };



    //HTTP请求获取Headers
    class httpAsync {
        varructor() {
        }
        async GetAsync(url) {
            var promise = new Promise(resolve => {
                http.get(url, res => {
                    resolve(res);
                });
            });
            return promise;
        }
    }


    //发送HTTP请求
    function httprequest(url,requestData,num,cb){
        request({
            url: url,
            method: "POST",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: requestData
        }, function(error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body)
                console.log(moment().format('YYYY-MM-DD HH:mm:ss'))
                console.log('http post req success') // 请求成功的处理逻辑
                cb()
            } else {
                console.log(moment().format('YYYY-MM-DD HH:mm:ss'))
                console.error('POST ERROR ' + url) // 请求成功的处理逻辑
                console.log(num)
                if (num <= 4){
                    num += 1;
                    setTimeout(function () {
                        httprequest(url,requestData,num,cb)
                    }, 1000*60);
                };
                cb();
            };
        });
    };

}).call(this);
